//
//  ESUNMapViewController.m
//  ESUN
//
//  Created by wang yongfeng on 13-12-4.
//  Copyright (c) 2013年 wang yongfeng. All rights reserved.
//

#import "ESUNMapViewController.h"
#import <MapKit/MapKit.h>
#import "MapMarkAnimation.h"
#import <CoreLocation/CoreLocation.h>
#import "LocationChange.h"
@interface ESUNMapViewController ()<MKMapViewDelegate>
{
    MKMapView *myMapView;
    CLLocationCoordinate2D myLocation;
    NSMutableArray *btnArray;
}
@end

@implementation ESUNMapViewController
@synthesize location2D;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        btnArray = [[NSMutableArray alloc] initWithCapacity:1];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.titleLabel setText:@"商铺地址"];
    [self.leftButton setHidden:NO];
    [self.rightButton setHidden:NO];
    [self.leftButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [self.leftButton addTarget:self action:@selector(clickBackBtn:) forControlEvents:UIControlEventTouchUpInside];
	// Do any additional setup after loading the view.
    myMapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, 64, 320, self.fHight - 64)];
    //地图类型
    [myMapView setMapType:MKMapTypeStandard];
    myMapView.delegate = self;//地图代理
    myMapView.showsUserLocation = YES;//开始定位用户位置
    //[myMapView setUserTrackingMode:MKUserTrackingModeFollow animated:YES];//用户位置跟踪模式
    [self.view addSubview:myMapView];
    double lat = 0.0f,lon=0.0f;
    //NSLog(@"BD_09:%.6f,%.6f",location2D.latitude,location2D.longitude);
    //百度坐标转为火星坐标
    BD09_TO_GCJ02(location2D.latitude, location2D.longitude, &lat, &lon);
    location2D = CLLocationCoordinate2DMake(lat, lon);
    //NSLog(@"GCJ02:%.6f,%.6f",location2D.latitude,location2D.longitude);
    [myMapView setCenterCoordinate:location2D];
    [myMapView setRegion:MKCoordinateRegionMake(location2D,MKCoordinateSpanMake(0.5,0.5))];
    [self addAnnomation];
    UIImageView *btnBg = [[UIImageView alloc] init];
    [btnBg setFrame:CGRectMake(0, 64, 320, 68/2)];
    [btnBg setImage:[UIImage imageNamed:@"iconbg_map"]];
    [self.view addSubview:btnBg];
    //三种导航方式
    NSArray *titleArray = @[@"map_driving2",@"map_bus2",@"map_walk2"];
    NSArray *titleArraySe = @[@"map_driving1",@"map_bus1",@"map_walk1"];
    for(int i = 0;i< 3;++i)
    {
        UIButton *btnNavi = [[UIButton alloc]  init];
        btnNavi.tag = i;
        [btnNavi setFrame:CGRectMake(40+105*i, 66, 30, 30)];
        [btnNavi setImage:[UIImage imageNamed:[titleArray objectAtIndex:i]] forState:UIControlStateNormal];
        [btnNavi setImage:[UIImage imageNamed:[titleArraySe objectAtIndex:i]] forState:UIControlStateSelected];
        [btnNavi addTarget:self action:@selector(clickNavigationType:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:btnNavi];
        [btnArray addObject:btnNavi];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillDisappear:(BOOL)animated
{
    myMapView.delegate = nil;
}

/*
 *地图的委托方法
 */
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    //定位到的用户位置
    //myMapView.centerCoordinate = userLocation.location.coordinate;
    myLocation = userLocation.location.coordinate;
}

/*
 *添加标记
 */
- (void)addAnnomation
{
    MapMarkAnimation *mark = [[MapMarkAnimation alloc] initWithCoordinate:location2D];
    mark.title = self.name;//@"标题";
    mark.subtitle = self.address;//@"目的地";
    [myMapView addAnnotation:mark];
}

/*
 *添加大头针的VIEW
 */

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
    if(annotation != mapView.userLocation)
    {
        static NSString *identifer = @"AnnotaionView";
        if([annotation  isKindOfClass:[MapMarkAnimation class]])
        {
            //标记
            MKAnnotationView *markView = [mapView dequeueReusableAnnotationViewWithIdentifier:identifer];
            if(markView == nil)
            {
                markView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifer];
            }
            markView.image = [UIImage imageNamed:@"icon_pitch1"];
            markView.canShowCallout = YES;
            return markView;
        }
    }
        return  nil;
}

/*
 *点击大头针弹出视图
 */
- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
    if([view isKindOfClass:[MapMarkAnimation class]])
    {
        //弹出的视图
    }
}

/*
 *选中弹出窗口
 */
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{
    
}

/*
 *选择导航方式
 */
-(void)clickNavigationType:(UIButton *)btn
{
    for(UIButton *tmp in btnArray)
    {
        [tmp setSelected:NO];
    }
    [btn setSelected:YES];
    CLLocationCoordinate2D startCoords = CLLocationCoordinate2DMake(myLocation.latitude,myLocation.longitude);;
    CLLocationCoordinate2D endCoords = CLLocationCoordinate2DMake(location2D.latitude,location2D.longitude);
    
    MKPlacemark *fromMark = [[MKPlacemark alloc] initWithCoordinate:startCoords addressDictionary:nil];
    MKPlacemark *toMark = [[MKPlacemark alloc] initWithCoordinate:endCoords addressDictionary:nil];
    
    MKMapItem *fromItem = [[MKMapItem alloc] initWithPlacemark:fromMark];
    MKMapItem *toItem = [[MKMapItem alloc] initWithPlacemark:toMark];
    
    //ios 7.0
    //删除之前的路径
    [myMapView removeOverlays:myMapView.overlays];
    MKDirectionsRequest *request = [[MKDirectionsRequest alloc] init];
    request.source = fromItem;
    request.destination = toItem;
    switch (btn.tag) {
        case 0:
        {
            
            request.transportType = MKDirectionsTransportTypeAutomobile;
            break;
        }
        case 1:
        {
            request.transportType = MKDirectionsTransportTypeAny;
            break;
        }
        case 2:
        {
            request.transportType = MKDirectionsTransportTypeWalking;
            break;
        }
        default:
            break;
    }
    //可以获得多条路线
    request.requestsAlternateRoutes = YES;
    MKDirections *directions = [[MKDirections alloc] initWithRequest:request];
    [directions calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse *response, NSError *error) {
        if (error) {
            NSLog(@"error:%@", error);
            ESUNAlertView *alert = [[ESUNAlertView alloc] initWithTitle:@"搜索路径失败" withDelegate:self];
            [alert show];
        }
        else {
            MKRoute *route = response.routes[0];
            [myMapView addOverlay:route.polyline];
        }
    }];
    /*
    if (SYSTEM_VERSION_LESS_THAN(@"6.0"))// ios6以下，调用google map
    {
        NSString *urlString = [[NSString alloc]
                               initWithFormat:@"http://maps.google.com/maps?saddr=%f,%f&daddr=%f,%f&dirfl=d",
                               startCoords.latitude,startCoords.longitude,endCoords.latitude,endCoords.longitude];
        NSURL *aURL = [NSURL URLWithString:urlString];
        //打开网页google地图
        [[UIApplication sharedApplication] openURL:aURL];
    }else// 直接调用ios自己带的apple map
    {
        //当前的位置
        //MKMapItem *currentLocation = [MKMapItem mapItemForCurrentLocation];
        //起点
        MKMapItem *currentLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:startCoords addressDictionary:nil]];
        //目的地的位置
        MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:endCoords addressDictionary:nil]];
        toLocation.name = @"目的地";
        NSArray *items = [NSArray arrayWithObjects:currentLocation, toLocation, nil];
        /*
         //keys
         MKLaunchOptionsMapCenterKey:地图中心的坐标(NSValue)
         MKLaunchOptionsMapSpanKey:地图显示的范围(NSValue)
         MKLaunchOptionsShowsTrafficKey:是否显示交通信息(boolean NSNumber)
         //MKLaunchOptionsDirectionsModeKey: 导航类型(NSString)
         {
         MKLaunchOptionsDirectionsModeDriving:驾车
         MKLaunchOptionsDirectionsModeWalking:步行
         }
         //MKLaunchOptionsMapTypeKey:地图类型(NSNumber)
         enum {
         MKMapTypeStandard = 0,
         MKMapTypeSatellite,
         MKMapTypeHybrid
         };
         */
    /*
        NSDictionary *options = nil;
        //walk
        if(btn.tag == 0)
        {
            options = @{
                        MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving,
                        MKLaunchOptionsMapTypeKey:
                            [NSNumber numberWithInteger:MKMapTypeStandard],
                        MKLaunchOptionsShowsTrafficKey:@YES
                        };
        }
        //driver
        if(btn.tag == 1)
        {
            options = @{
                        MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving,
                        MKLaunchOptionsMapTypeKey:
                            [NSNumber numberWithInteger:MKMapTypeStandard],
                        MKLaunchOptionsShowsTrafficKey:@YES
                        };
        }
        //bus
        if(btn.tag == 2)
        {
            options = @{
                        MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving,
                        MKLaunchOptionsMapTypeKey:
                            [NSNumber numberWithInteger:MKMapTypeStandard],
                        MKLaunchOptionsShowsTrafficKey:@YES
                        };
        }
        
        //打开苹果自身地图应用，并呈现特定的item
        [MKMapItem openMapsWithItems:items launchOptions:options];
    }
     */
}

- (MKOverlayRenderer *)mapView:(MKMapView *)mapView
            rendererForOverlay:(id<MKOverlay>)overlay{
    MKPolylineRenderer *renderer = [[MKPolylineRenderer alloc] initWithOverlay:overlay];
    renderer.lineWidth = 2.0;
    renderer.strokeColor = [UIColor blueColor];
    return renderer;
}
/*
 *返回
 */
- (void)clickBackBtn:(UIButton *)btn
{
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

@end
